package com.zs.letcode.linked_list;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 复制带随机指针的链表
 * 给你一个长度为 n 的链表，每个节点包含一个额外增加的随机指针 random ，该指针可以指向链表中的任何节点或空节点。
 * <p>
 * 构造这个链表的深拷贝。深拷贝应该正好由 n 个 全新 节点组成，其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点，并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
 * <p>
 * 例如，如果原链表中有 X 和 Y 两个节点，其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ，同样有 x.random --> y 。
 * <p>
 * 返回复制链表的头节点。
 * <p>
 * 用一个由n个节点组成的链表来表示输入/输出中的链表。每个节点用一个[val, random_index]表示：
 * <p>
 * val：一个表示Node.val的整数。
 * random_index：随机指针指向的节点索引（范围从0到n-1）；如果不指向任何节点，则为null。
 * 你的代码 只 接受原链表的头节点 head 作为传入参数。
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
 * 输出：[[7,null],[13,0],[11,4],[10,2],[1,0]]
 * 示例 2：
 * <p>
 * <p>
 * <p>
 * 输入：head = [[1,1],[2,1]]
 * 输出：[[1,1],[2,1]]
 * 示例 3：
 * <p>
 * <p>
 * 输入：head = [[3,null],[3,0],[3,null]]
 * 输出：[[3,null],[3,0],[3,null]]
 * 示例 4：
 * <p>
 * 输入：head = []
 * 输出：[]
 * 解释：给定的链表为空（空指针），因此返回 null。
 * <p>
 * 提示：
 * <p>
 * 0 <= n <= 1000
 * -10000 <= Node.val <= 10000
 * Node.random为空（null）或指向链表中的节点。
 * 相关标签
 * 哈希表
 * 链表
 * <p>
 * 作者：力扣 (LeetCode)
 * 链接：https://leetcode-cn.com/leetbook/read/linked-list/fdi26/
 * 来源：力扣（LeetCode）
 * 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
 *
 * @author madison
 * @description
 * @date 2021/5/21 12:49
 */
public class Chapter14 {
    public static void main(String[] args) {

    }

    private static class Solution {
        /**
         * 方法 1：回溯
         */
        Map<Node, Node> visitedMap = new HashMap<>();

        public Node copyRandomList(Node head) {
            if (Objects.isNull(head)) {
                return null;
            }
            // If we have already processed the current node, then we simply return the cloned version of it.
            if (this.visitedMap.containsKey(head)) {
                return this.visitedMap.get(head);
            }
            // Create a new node with the value same as old node. (i.e. copy the node)
            Node node = new Node(head.val, null, null);
            // Save this value in the hash map. This is needed since there might be
            // loops during traversal due to randomness of random pointers and this would help us avoid
            // them.
            this.visitedMap.put(head, node);

            // Recursively copy the remaining linked list starting once from the next pointer and then from
            // the random pointer.
            // Thus we have two independent recursive calls.
            // Finally we update the next and random pointers for the new node created.
            node.next = this.copyRandomList(head.next);
            node.random = this.copyRandomList(head.random);
            return node;
        }

        /**
         * 方法 2： O(N)O(N) 空间的迭代
         *
         * @param head
         * @return
         */
        Map<Node, Node> visited = new HashMap<>();

        public Node copyRandomList1(Node head) {
            if (Objects.isNull(head)) {
                return null;
            }
            Node oldNode = head;

            // Creating the new head node.
            Node newNode = new Node(oldNode.val);
            this.visited.put(oldNode, newNode);

            // Iterate on the linked list until all nodes are cloned.
            while (oldNode != null) {
                // Get the clones of the nodes referenced by random and next pointers.
                newNode.random = this.getCloneNode(oldNode.random);
                newNode.next = this.getCloneNode(oldNode.next);

                // Move one step ahead in the linked list.
                oldNode = oldNode.next;
                newNode = newNode.next;
            }
            return visited.get(head);
        }

        private Node getCloneNode(Node node) {
            // If the node exists then
            if (Objects.nonNull(node)) {
                // Check if the node is in the visited dictionary
                if (!visited.containsKey(node)) {
                    // If its in the visited dictionary then create a new node, add to the dictionary and return it
                    visited.put(node, new Node(node.val, null, null));
                }
                // Otherwise return the new node reference from the dictionary
                return visited.get(node);
            }
            return null;
        }

        /**
         * 方法 3：O(1)O(1) 空间的迭代
         */
        public Node copyRandomList2(Node head) {
            if (Objects.isNull(head)) {
                return null;
            }
            // Creating a new weaved list of original and copied nodes.
            Node ptr = head;
            while (Objects.nonNull(ptr)) {
                // Cloned node
                Node newNode = new Node(ptr.val);
                newNode.next = ptr.next;
                ptr.next = newNode;
                ptr = newNode.next;
            }
            ptr = head;
            while (Objects.nonNull(ptr)) {
                ptr.next.random = (ptr.random != null) ? ptr.random.next : null;
                ptr = ptr.next.next;
            }
            Node ptr_old_list = head;
            Node ptr_new_list = head.next;
            Node head_old = head.next;
            while (Objects.nonNull(ptr_old_list)) {
                ptr_old_list.next = ptr_old_list.next.next;
                ptr_new_list.next = (ptr_new_list.next != null) ? ptr_new_list.next.next : null;
                ptr_old_list = ptr_old_list.next;
                ptr_new_list = ptr_new_list.next;
            }
            return head_old;
        }

        public Node copyRandomList3(Node head) {
            if (Objects.isNull(head)) {
                return null;
            }
            Map<Node, Node> map = new HashMap<>();
            Node result = new Node(head.val);
            Node oldNode = result;
            map.put(head, oldNode);
            while (Objects.nonNull(oldNode)) {
                Node random = null;
                if (Objects.nonNull(head.random) &&
                        map.containsKey(head.random)) {
                    random = map.get(head.random);
                }
                Node temp = new Node(head.next.val);
                map.put(head.next, temp);
                oldNode.next = temp;
                oldNode.random = random;
                oldNode = temp;
                head = head.next;
            }
            return result;
        }
    }

    private static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }

        public Node(int val, Node next, Node random) {
            this.val = val;
            this.next = next;
            this.random = random;
        }
    }
}
